//
//  HomePageModel.swift
//  Drop
//
//  Created by zhuxuhong on 2018/3/17.
//  Copyright © 2018年 zhuxuhong. All rights reserved.
//

import UIKit

class HomePageDataSource: NSObject, UIPageViewControllerDataSource {

    var pageData: [String] = []
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        var index = indexOfViewController(viewController as! DropListVC)
        if (index == 0) || (index == NSNotFound) {
            return nil
        }
        
        index -= 1
        return viewControllerAtIndex(index, storyboard: viewController.storyboard!)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        var index = indexOfViewController(viewController as! DropListVC)
        if index == NSNotFound {
            return nil
        }
        
        index += 1
        if index == pageData.count {
            return nil
        }
        return viewControllerAtIndex(index, storyboard: viewController.storyboard!)
    }
    
    func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> DropListVC? {
        // 返回要展示的controller
        if (self.pageData.count == 0) || (index >= self.pageData.count) {
            return nil
        }
        
        // 创建controller并绑定数据
        let dataViewController = storyboard.instantiateViewController(withIdentifier: "DropListVC") as! DropListVC
        
        dataViewController.dataObject = pageData[index]
        
        return dataViewController
    }
    
    // 返回当前controller的index，便于上下页时计算使用
    private func indexOfViewController(_ viewController: DropListVC) -> Int {
        return pageData.index(of: viewController.dataObject) ?? NSNotFound
    }
}
